package com.wondream.myframework.app.common.util;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * Apollo配置类
 */
@Slf4j
@Service
public class ApolloBaseConfig {

    /**
     * 获取默认application namespace配置的值
     */
    public String getConfigByKey(String configKey, String defaultValue) {
        if (StringUtils.isBlank(configKey)) {
            return defaultValue;
        }
        try {
            Config config = ConfigService.getAppConfig();
            if (null != config) {
                return config.getProperty(configKey, defaultValue);
            }
        } catch (Exception e) {
            log.error("getConfigByKey has exception.", e);
        }
        return defaultValue;
    }

    /**
     * 根据namespace获取apollo配置的值
     */
    public String getConfigByKey(String nameSpace, String configKey, String defaultValue) {
        if (StringUtils.isBlank(configKey)) {
            return defaultValue;
        }
        Config config = null;
        try {
            if (StringUtils.isBlank(nameSpace)) {
                config = ConfigService.getAppConfig();
            } else {
                config = ConfigService.getConfig(nameSpace);
            }
            if (null != config) {
                return config.getProperty(configKey, defaultValue);
            }
        } catch (Exception e) {
            log.error("getConfigByKeyNameSpace has exception.", e);
        }
        return defaultValue;
    }

}
